import Taro, { Component } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { $Req } from "@utils";
import {
  AtList,
  AtListItem,
  AtButton,
  AtActionSheet,
  AtCheckbox,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtInput,
  AtActionSheetItem,
  AtFloatLayout,
  AtCard
} from "taro-ui";
import "./index.scss";

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "我的收益",
  };

  constructor(props) {
    super(...arguments);
    this.state = {
      currentTab: 0,
      showFlag: false,
      // 显示提现方式
      showAction: false,
      showLayer: false,
      checkboxOption: [
        {
          value: "1",
          label: "提现到微信零钱",
        },
        {
          value: "0",
          label: "提现到银行卡",
        },
      ],
      checkedList: ["0"],
      money: 0,
      bankIndex: 0,
      TxMoney: "",
      kaList: [],
      bankVal: "",
      bankListShow: false,
      txxy: false,
      xyContent: "暂无",
      zrData: {},
      currUser: null
    };
  }

  componentDidShow() {
    let ordersNo = Taro.getStorageSync("ordersNo");
    let syPay = Taro.getStorageSync("syPay");
    if (ordersNo && syPay) {
      return this.postZzsy()
    }

    this.getMyProfit();
    this.getBankCard();
    this.getConf();
    this.setState({
      showFlag: false,
      showAction: false,
    })
  }

  // 获取收益
  async getConf() {
    const { code, message, data } = await $Req({
      type: "get",
      url: "/order/getSysOrderConf",
      data: {},
    });
    if (!data) return;
    if (data.withdrawalRules) {
      this.setState({
        xyContent: data.withdrawalRules
      });
    }
    
  }

  // 获取收益
  async getMyProfit() {
    const {
      userModel: { userInfo },
    } = this.props;
    const { code, message, data } = await $Req({
      type: "get",
      url: "/indexUser/getUserIntegral",
      data: {},
    });
    if (!data) return;

    this.setState({
      money: data.benefit,
    });
  }

  // 获取银行卡
  async getBankCard() {
    const { data } = await $Req({
      type: "get",
      url: "/indexUser/getBankCard",
      data: {},
    });
    if (!data.length) return;

    this.setState({
      kaList: data,
      bankVal: `${data[0].bankName}(${data[0].cardId.substr(
        data[0].cardId.length - 4,
        data[0].cardId.length
      )})`,
    });
  }

  async postMsg() {

    let { TxMoney, kaList, bankIndex, checkedList } = this.state;

    let postData = {
      ammount: TxMoney,
      cashOutType: checkedList[0]
    };

    if(checkedList[0] == '0') {
      // 零钱提现
      postData.bandId = kaList[bankIndex].bankId;
      postData.bandNum = kaList[bankIndex].cardId;
      postData.bandUserName = kaList[bankIndex].cardName;
    }
 
    const { data, message } = await $Req({
      type: "post",
      url: "/cashOutOrder/addCashOutOrder",
      data: postData,
    });
    if (!data) return;
    Taro.showToast({
      title: message || '接口失败'
    })

    this.getMyProfit();
  }

  layerClose = () => {
    this.setState({
      showLayer: false,
      showAction: false,
      zrData: {},
      currUser: null
    })
  }

  findUserPhone = async () => {
    let { userPhone } = this.state.zrData;

    if (!(/^1[3456789]\d{9}$/.test(userPhone))) {
      Taro.showToast({
        title: "手机号码错误!",
        icon:"none"
      })
      return false;
    }

    const { data, code } = await $Req({
      type: "post",
      url: "/user/getUserList",
      data: { userPhone, start: 1, length: 9999999 },
    });
    
    if (code == 200) {
      this.setState({
        currUser: data.data[0]
      })
    } else {
      Taro.showToast({
        title: "没有查询到任何用户",
        icon: "none"
      })
    }
  }

  postZzsy = async () => {
    if(!this.state.currUser) {
      Taro.showToast({
        title: "为了确保您的财产安全，请先查询用户确认后在进行转账操作!",
        icon:"none"
      })
      return false;
    }

    let { userPhone, transferPrice } = this.state.zrData;

    if (!(/^1[3456789]\d{9}$/.test(userPhone))) {
      Taro.showToast({
        title: "手机号码错误!",
        icon:"none"
      })
      return false;
    }

    if (!transferPrice) {
      Taro.showToast({
        title: "转让金额不能为空或0!",
        icon:"none"
      })
      return false;
    }

    if (isNaN(transferPrice)) {
      Taro.showToast({
        title: "转让金额必须是数字!",
        icon:"none"
      })
      return false;
    }

    // 跳转到支付密码页面

    const {
      userModel: { userInfo },
    } = this.props;

    // 检查支付密码
    let abc = await $Req({
      type: "get",
      url: "/indexUser/checkHavePayPassword",
      data: { userId: userInfo.userId },
    });
    let payFlag = Taro.getStorageSync("syPay");
    
    if (abc.code == 200) {
      if (!payFlag) {
        // 有密码
        if (abc.data) {
          Taro.navigateTo({
            url: `/pages/user/payPwd/index?flag=1&ordersNo=1&yzpwd=true`
          })
          return false;
        }
        // 没密码 
        else {
          Taro.navigateTo({
            url: '/pages/user/payPwd/index'
          })
          return false;
        }
      }
    }

    const { data, code, message } = await $Req({
      type: "post",
      url: "/user/transferProfit",
      data: { userPhone, transferPrice },
    });
    
    if (code == 200) {
      this.setState({
        showLayer: false,
        zrData: {},
        currUser: null
      }, () => {
        Taro.showToast({
          title: "转让收益成功!",
          icon:"none"
        })

        this.getMyProfit();
      })
    } else {
      Taro.showToast({
        title: message,
        icon: "none"
      })
    }

    Taro.removeStorageSync("syPay");
    Taro.removeStorageSync("ordersNo");
  }

  render() {
    let { showLayer, zrData, currUser } = this.state;
    return (
      <View className="page-user-income">
        <View className="at-row">
          <View className="at-col c0">
            <View className="at-row at-row__align--center r1">
              <View className="at-col c11">
                <Text>当前收益（元）</Text>
              </View>
            </View>
            <View className="at-row at-row__justify--between at-row__align--center r2">
              <View className="at-col c21">
                <Text className="t1">{this.state.money}</Text>
              </View>
              <AtButton
                  type="primary"
                  circle
                  size="small"
                  onClick={() => {
                    this.setState({
                      showLayer: true,
                      showAction: false
                    })
                  }}
                >
                  转让收益
                </AtButton>
                <AtFloatLayout isOpened={showLayer} title="转让收益" onClose={this.layerClose}>
                  <View  className="at-row at-row__justify--between at-row__align--center r2">
                    <AtInput
                      clear
                      maxLength={11}
                      name='phone'
                      title='手机号码'
                      type='phone'
                      placeholder='手机号码'
                      value={zrData.userPhone}
                      onChange={val => {
                        this.state.zrData.userPhone = val;
                        this.setState({
                          zrData: this.state.zrData
                        })
                      }}
                    />
                    <AtButton
                      type="primary"
                      circle
                      size="small"
                      onClick={this.findUserPhone}
                    >
                      查询用户
                    </AtButton>
                  </View>
                  <AtInput
                    name='value5'
                    title='转账金额'
                    type='digit'
                    placeholder='请输入转账金额'
                    value={zrData.transferPrice}
                    onChange={ val => {
                      this.state.zrData.transferPrice = val;
                      this.setState({
                        zrData: this.state.zrData
                      })
                    }}
                  />
                  {
                    currUser ? 
                    <AtCard
                      note={currUser.userPhone}
                      extra={currUser.sex ? "男" : "女"}
                      title={currUser.name}
                      thumb={"手机号：" + currUser.userPhoto}
                    >
                      请您确认好信息后再进行转账操作！
                    </AtCard>
                    :
                    null
                  }

                  <View style={{ marginTop:"10PX" }}>
                    <AtButton
                      type="primary"
                      circle
                      size="small"
                      onClick={this.postZzsy}
                    >
                      提交转账
                    </AtButton>
                  </View>
                </AtFloatLayout>
            </View>
            <View className="at-row at-row__justify--between at-row__align--center r3">
              <View className="at-col at-col-10 c31">
                <Text>可提现(元)</Text>
                <Text className="t2">{this.state.money}</Text>
                <Text className="t3" onClick={
                  () => {
                    this.setState({
                      txxy: true
                    })
                  }
                }>查看提现规则</Text>
              </View>
              <View className="at-col at-col-2 c32">
                <AtButton
                  type="primary"
                  circle
                  size="small"
                  onClick={() => {
                    if (this.state.money > 0) {
                      console.log(this.state.checkedList);
                      if (this.state.checkedList[0] == '0') {
                        if (this.state.kaList.length) {
                          this.setState({
                            showFlag: true,
                            showAction: false
                          }); 
                        } else {
                          Taro.showToast({
                            title: "请绑定银行卡在进行提现",
                            icon: "none"
                          })
                        }
                      } else {
                        this.setState({
                          showFlag: true,
                          showAction: false
                        }); 
                      }
                    } else {
                      Taro.showToast({
                        title: "不能提现，没有足够的金额",
                        icon: "none"
                      })
                    }
                    
                  }}
                >
                  提现
                </AtButton>
              </View>
            </View>
          </View>
        </View>
        <AtList hasBorder={false}>
          <AtListItem title='提现方式' arrow='right' 
              onClick={() => {
                this.setState({
                  showAction: true
                });
              }} 
            />
          <AtListItem
            title="收益记录"
            arrow="right"
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/user/sydetails/index'
              })
            }}
          />
          <AtListItem
            title="提现记录"
            arrow="right"
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/user/txdetails/index'
              })
            }}
          />
          <AtListItem
            title="收益转让记录"
            arrow="right"
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/user/transferRecord/index'
              })
            }}
          />
          <AtListItem
            title="支付密码管理"
            arrow="right"
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/user/payPwd/index'
              })
            }}
          />
        </AtList>
        {/* 提现方式 */}
        <AtActionSheet isOpened={this.state.showAction} title="选择提现方式" >
          <AtCheckbox
            options={this.state.checkboxOption}
            selectedList={this.state.checkedList}
            onChange={(v, op) => {
              this.setState({
                checkedList: [v[1]],
              });
            }}
          />
        </AtActionSheet>
        {/* <AtFloatLayout
          isOpened={this.state.showAction}
          title="这是个标题"
        ></AtFloatLayout> */}

        {/* 提现弹窗 */}
        <AtModal isOpened={this.state.showFlag} onClose={
          () => {
            this.setState({
              showFlag: false
            })
          }
        }>
          <AtModalHeader>提现方式</AtModalHeader>
          <AtModalContent>
            <View style="margin-bottom: 20px;">
              提现到
              {this.checkedList == "1" ? (
                <Text style="color:#17A8E6;">微信零钱</Text>
              ) : (
                <Text onClick={() => {
                  this.setState({
                    bankListShow: true,
                  })
                }} style="color:#17A8E6;">
                  {this.state.bankVal}
                </Text>
              )}
            </View>
            <View>
              <View style="font-size:12px; color: #999">提现金额</View>
              <View>
                {
                  this.state.showFlag ? 
                    <AtInput
                      name="value"
                      type="bumber"
                      placeholder="请输入提现金额"
                      value={this.state.TxMoney}
                      onChange={(e) => {
                        this.setState({
                          TxMoney: e,
                        });
                      }}
                    />
                  : 
                    null
                }
                
              </View>
            </View>
            <View style="margin-top: 10px; color: #999; font-size:12px;">
              当前零钱余额 {this.state.money} 元,
              <Text
                style="color:#17A8E6;"
                onClick={() => {
                  this.setState({
                    TxMoney: this.state.money,
                  });
                }}
              >
                全部提现
              </Text>
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button
              onClick={() => {
                this.setState({
                  showFlag: false
                });
              }}
            >
              取消
            </Button>
            <Button
              onClick={() => {
                this.setState({
                  showFlag: false
                }, () => {
                  this.postMsg();
                });
              }}
            >
              确定
            </Button>
          </AtModalAction>
        </AtModal>

        {/* 选择银行卡 */}
        <AtActionSheet title="选择银行卡" isOpened={this.state.bankListShow} onClose={
          () => {
            this.setState({
              bankListShow: false
            })
          }
        }>
          {this.state.kaList.map((el, index) => (
            <AtActionSheetItem onClick={
              () => {
                this.setState({
                  bankVal: `${el.bankName}(${el.cardId.substr(el.cardId.length - 4, el.cardId.length)})`,
                  bankListShow: false,
                  bankIndex: index
                })
              }
            }>
              {el.bankName}(
              {el.cardId.substr(el.cardId.length - 4, el.cardId.length)})
            </AtActionSheetItem>
          ))}
        </AtActionSheet>
        {/* 提现规则 */}

        <AtModal
          isOpened={this.state.txxy}
          title='提现规则'
          confirmText='确认'
          onClose={ () => {
            this.setState({
              txxy: false
            })
          }}
          onCancel={ () => {
            this.setState({
              txxy: false
            })
          } }
          onConfirm={ () => {
            this.setState({
              txxy: false
            })
          } }
          content={this.state.xyContent}
        />
      </View>
    );
  }
}
